/*
 * DoorState.java
 * iRoomMonitor1.0
 * 11/13/10
 */

package RoomNanny.SpotSensors;

import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.peripheral.IAccelerometer3D;

import java.io.IOException;



/**
 *This class builds and calculates the door states from accelerometer readings
 *
 * @author Chirs Ammons
 */
public class DoorState implements DoorMotion{
    //accelerometer initialization
    private IAccelerometer3D accelerometer = EDemoBoard.getInstance()
            .getAccelerometer();
    // Door States
    private int movement = 0; // numerical values set for motion states
    // Int values for door motion states
    /* 0: closing
     * 1: Moving
     * 2: Opening
     * 3: still
     */
    // Accelerometer recordings used to calculate the door state
    private double accelReadingX = 0;
    private double accelReadingY = 0;
    private double accelReadingZ = 0;
    private double totalAccel=0;

    /**
     * Basic method that the Listener calls.
     * @return
     */
    public int getState(){
        accelReadingX = 0;
        accelReadingY = 0;
        accelReadingZ = 0;
        totalAccel=0;
        this.getAccel();
        this.calculateMotion();
        return movement;
    }

    /**
     * this method takes the accelerometer readings and calculates basic door
     * movement from them.
     *
     * Our sample time is not fast enough from the sensor class to make accurate
     * position readings so we just went with motion states
     * 
     */
    public void getAccel(){
        try {
            totalAccel=accelerometer.getAccel();
            accelReadingX = accelerometer.getAccelX();
            accelReadingY = accelerometer.getAccelY();
            accelReadingZ = accelerometer.getAccelZ();
        } catch (IOException ex) {
            System.out.println("Error reading accelerometer: " + ex);
        }
    }
    /**
     * calculates the motion of the door
     *
     * @return returns the String of the state of the door
     */
    public int calculateMotion() {
        if (totalAccel-1>0){
            if (accelReadingZ>0){// door opening set to number 2
            movement = 2;

            }
            else if (accelReadingZ<0){// door closing set to 0
             movement = 0;
            }
        }
        else{// door still set to 3
             movement = 3;
        }


       return movement;

    }


}
